<?php

declare (strict_types = 1);

namespace app\admin\controller\admin;

use app\admin\controller\Base;
use app\admin\model\admin\User as UserModel;
use app\admin\service\admin\Auth as AuthService;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

/**
 * 后台管理员用户控制器
 */
class User extends Base
{
    /**
     * 获取当前登录的用户信息
     * @return Json
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function info(): Json
    {
        return $this->returnSuccess([
            // 用户信息
            'userInfo' => UserModel::detail((new AuthService)->getLoginUserId(),['role']),
            // 菜单权限
            'roles' => AuthService::getLoginPermissions(),
        ]);
    }

    /**
     * 管理员列表
     * @return Json
     * @throws DbException
     */
    public function list(): Json
    {
        $model = new UserModel;
        $list = $model->getList($this->request->param());
        return $this->returnSuccess(compact('list'));
    }

    /**
     * 添加管理员
     * @return Json
     */
    public function add(): Json
    {
        // 新增记录
        $model = new UserModel;
        if ($model->add($this->postForm())) {
            return $this->returnSuccess('添加成功');
        }
        return $this->returnError($model->getError() ?: '添加失败');
    }

    /**
     * 更新管理员
     * @return Json
     */
    public function edit(): Json
    {

        $postData = $this->postData();
        // 管理员详情
        $model = UserModel::detail($postData['userId']);
        // 更新记录
        if ($model->edit($this->postForm())) {
            return $this->returnSuccess('更新成功');
        }
        return $this->returnError($model->getError() ?: '更新失败');
    }

    /**
     * 删除管理员
     * @return Json
     */
    public function deleted(): Json
    {
        $postData = $this->postData();
        // 管理员详情
        $model = UserModel::detail($postData['userId']);
        if (!$model->setDelete()) {
            return $this->returnError($model->getError() ?: '删除失败');
        }
        return $this->returnSuccess('删除成功');
    }

    /**
     * 更新当前管理员信息
     * @return Json
     */
    public function updateInfo(): Json
    {
        // 管理员详情
        $model = UserModel::detail((new AuthService)->getLoginUserId());
        if (!$model) {
            return $this->returnError('更新失败,用户不存在');
        }
        // 更新当前管理员信息
        if ($model->renew($this->postForm())) {
            return $this->returnSuccess('更新成功');
        }
        return $this->returnError($model->getError() ?: '更新失败');
    }
}
